package handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.json.JSONObject;

public class RequestHandler extends HttpServlet {
    private static final long serialVersionUID = 6568558603123066897L;
    private Random random;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String referer = req.getHeader("referer");
        String protocol = req.isSecure() ? "https://" : "http://";
        if (Objects.nonNull(referer) && referer.length() > 0) {
            String host = req.getHeader("host");
            String contextPath = req.getContextPath();
            String expectedRefererUrl = protocol + host + contextPath + "/json.html";
            // 如果期望的来源地址是指定地址
            if (expectedRefererUrl.equals(referer)) {
                resp.setContentType("text/plain");
                Map<String, Object> properties = new ConcurrentHashMap<>();
                properties.put(boolean.class.getSimpleName(), random.nextBoolean());
                properties.put(int.class.getSimpleName(), random.nextInt(Integer.MAX_VALUE) + 1);
                properties.put(long.class.getSimpleName(), random.nextLong() + 1);
                properties.put(float.class.getSimpleName(), random.nextFloat());
                properties.put(double.class.getSimpleName(), random.nextDouble());
                JSONObject object = new JSONObject(properties);
                PrintWriter out = resp.getWriter();
                out.print(object.toString());
            }
        }
    }

    @Override
    public void init() throws ServletException {
        super.init();
        random = new Random();
    }
}
